package router

import (
	"common/config"
	"common/rpc"
	"gate/api"
	"gate/auth"
	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
	"net/http"
	"time"
)

// RegisterRouter 注册路由
func RegisterRouter() *gin.Engine {
	if config.Conf.Log.Level == "DEBUG" {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	//初始化grpc的client gate是作为grpc的客户端 去调用user grpc服务
	rpc.Init()
	r := gin.Default()

	// 使用中间件
	r.Use(auth.Cors())
	// 设置每秒不超过两个请求的限制
	limiter := rate.NewLimiter(rate.Every(time.Second/5), 5)
	// 使用中间件
	r.Use(func(c *gin.Context) {
		if !limiter.Allow() {
			c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
				"error": "Too many requests",
			})
			return
		}
		c.Next()
	})
	userHandler := api.NewUserHandler()
	r.POST("/register", userHandler.Register)                  //注册登录
	r.POST("/forget_password", userHandler.ForgetPassword)     //忘记密码
	r.POST("/send_sms", userHandler.SendSms)                   //发送验证码
	r.POST("/get_notice", userHandler.GetNotice)               //公告详情
	r.Any("/CallbackPay", userHandler.CallbackPay)             //钱包支付回调处理
	r.Any("/alipayCallbackPay", userHandler.AlipayCallbackPay) //支付宝支付回调处理
	return r
}
